package util

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"regexp"
	"strconv"
	"time"
)



func SaveToImage(data string) string {
	b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, data)
	if !b {
		return ""
	}
	path := "upload/image"
	re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
	allData := re.FindAllSubmatch([]byte(data), 2)
	fileType := string(allData[0][1]) //png ，jpeg 后缀获取

	base64Str := re.ReplaceAllString(data, "")

	date := time.Now().Format("2006-01-02")
	if ok := IsFileExist(path + "/" + date); !ok {
		os.MkdirAll(path+"/"+date, 0755)
	}

	curFileStr := strconv.FormatInt(time.Now().UnixNano(), 10)

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	n := r.Intn(99999)

	var file string = path + "/" + date + "/" + curFileStr + strconv.Itoa(n) + "." + fileType
	byte, _ := base64.StdEncoding.DecodeString(base64Str)

	err := ioutil.WriteFile(file, byte, 0666)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	return file
}

//判断文件是否存在

func IsFileExist(filename string) bool {
	_, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return false
	}
	return true
}
